<template>
  <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <Bread
      first="个人中心"
      second="基本资料"
      style="margin-bottom: 20px"
    ></Bread>
    <el-form
      :model="infoForm"
      :rules="infoRuels"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="infoForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="infoForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="infoForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="resetInfo">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import { updateUserInfoApi } from '../../api/user'
export default {
  name: '',
  data () {
    return {
      // 表单信息对象
      infoForm: {
        username: '',
        nickname: '',
        email: ''
      },
      // 验证规则对象
      infoRuels: {
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称是1-10个非空字符',
            trigger: ['blur', 'change']
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur', 'change']
          },
          {
            pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/,
            message: '邮箱格式不正确',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created () {
    setInterval(() => {
      this.infoForm = this.userInfo
    }, 100)
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['AgetUserInfo']),
    updateUserInfo () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const res = await updateUserInfoApi(this.infoForm)
          if (res.data.code === 0) {
            this.$message({
              type: 'success',
              message: '基本信息更新成功'
            })
            this.AgetUserInfo()
          }
        }
      })
    },
    // 重置基本信息表单
    resetInfo () {
      this.infoForm = { ...this.userInfo }
      this.$refs.formRef.resetFields()
    }
  }
}
</script>
<style lang='less'  scoped>
.el-form {
  width: 40%;
}
</style>
